# 使用dbscan 三维数据进行密度聚类

import pandas as pd    # 读取csv 文件
import matplotlib.pyplot as plt   # 画图
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler


# 0 读取csv文件

file_path = '202412\\花洒分类\\files\\左0-2000ml-2-2024-12-10-22-43-58_point_cloud.csv'
df = pd.read_csv(file_path)
# print(df.head())

frame_index_all = list(set(df['FrameIndex']))
# print(frame_index_all)

# for frame_index in frame_index_all[:10]:

# 1 对需要的坐标进行画图
frame_index = 2 
# print(df['FrameIndex'])
frame_data = df[df['FrameIndex'] == frame_index].copy()
print(frame_data.shape)
Xyz = frame_data[[' X', '     Y', '       Z']]
# print(frame_data)

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

scatter = ax.scatter(frame_data[' X'], frame_data['     Y'], frame_data['       Z'], color='blue', label=f'FameIndex_{frame_index}')
# 设置图像标题和标签
ax.set_title("DBSCAN Clustering Results in 3D", fontsize=14)
ax.set_xlabel("X", fontsize=12)
ax.set_ylabel("Y", fontsize=12)
ax.set_zlabel("Z", fontsize=12)
# 添加图例
ax.legend(loc="upper right")
plt.savefig(f'202412\\花洒分类\\result_3D\\左0-2000ml-2-2024-12-10-22-43-58_point_cloud_{frame_index}.png')
plt.show()
# plt.close() 

# 2 使用聚类算法对需要的坐标进行画图

# 对数据进行标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(Xyz)

# 使用DBSCAN进行聚类
dbscan = DBSCAN(eps=0.8, min_samples=11)   # 调整聚类的半径 和最小阈值
labels = dbscan.fit_predict(X_scaled)
# print(labels)

# 将结果加入原数据中
frame_data['Cluster'] = labels

# 可视化结果
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
unique_labels = set(labels)
print(unique_labels)

# 使用不同颜色绘制每个聚类的点
for label in unique_labels:
    label_data = frame_data[frame_data['Cluster'] == label]
    scatter = ax.scatter( label_data[' X'], label_data['     Y'], label_data['       Z'], label=f'Cluster {label}')

# 3 展示画图的结果

ax.set_title("DBSCAN Clustering Results in 3D", fontsize=14)
ax.set_xlabel("X", fontsize=12)
ax.set_ylabel("Y", fontsize=12)
ax.set_zlabel("Z", fontsize=12)
# 添加图例

ax.legend(loc="upper right")
plt.savefig(f'202412\\花洒分类\\result_3D\\左0-2000ml-2-2024-12-10-22-43-58_point_cloud_{frame_index}_cluster.png')
plt.show()
plt.close()
# 4 保存
